// 用户数据（实际应由后端校验，这里仅做前端演示，后端会校验）
const user = { username: 'tanbaolong', password: '700704181..Tan' };

// 登录逻辑
loginBtn.onclick = function() {
  const u = adminUser.value.trim();
  const p = adminPass.value;
  fetch('admin_api.php?action=login', {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify({ username: u, password: p })
  })
  .then(res => res.json())
  .then(data => {
    if (data.success) {
      loginBox.style.display = 'none';
      settingBox.style.display = '';
      loadSetting();
    } else {
      loginMsg.textContent = data.msg || '登录失败';
    }
  });
};

function showPlatformKeyInput() {
  const platform = apiPlatform.value;
  document.querySelectorAll('.platform-key').forEach(input => {
    if (input.dataset.platform === platform) {
      input.style.display = '';
    } else {
      input.style.display = 'none';
    }
  });
}
apiPlatform.onchange = showPlatformKeyInput;
// 初始化时也调用一次
window.addEventListener('DOMContentLoaded', showPlatformKeyInput);

function loadSetting() {
  fetch('admin_api.php?action=get')
    .then(res => res.json())
    .then(cfg => {
      siteTitle.value = cfg.siteTitle || '';
      apiPlatform.value = cfg.apiPlatform || 'amap';
      amapKey.value = cfg.amapKey || '';
      qweatherKey.value = cfg.qweatherKey || '';
      qweatherHost.value = cfg.qweatherHost || '';
      qweatherJwt.value = cfg.qweatherJwt || '';
      aliyunAppCode.value = cfg.aliyunAppCode || '';
      showPlatformKeyInput();
    });
}

saveBtn.onclick = function() {
  fetch('admin_api.php?action=save', {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify({
      siteTitle: siteTitle.value.trim(),
      apiPlatform: apiPlatform.value,
      amapKey: amapKey.value.trim(),
      qweatherKey: qweatherKey.value.trim(),
      qweatherHost: qweatherHost.value.trim(),
      qweatherJwt: qweatherJwt.value.trim(),
      aliyunAppCode: aliyunAppCode.value.trim()
    })
  })
  .then(res => res.json())
  .then(data => {
    settingMsg.textContent = data.success ? '保存成功' : (data.msg || '保存失败');
    setTimeout(()=>settingMsg.textContent='', 2000);
  });
};

logoutBtn.onclick = function() {
  fetch('admin_api.php?action=logout').then(()=>{
    settingBox.style.display = 'none';
    loginBox.style.display = '';
    adminPass.value = '';
  });
}; 